package com.thinvent.remotepassword.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thinvent.remotepassword.dto.ExcelRowData;
import com.thinvent.remotepassword.entity.WikiDoc;
import com.thinvent.remotepassword.entity.WikiDocData;
import com.thinvent.remotepassword.mapper.WikiDocMapper;
import com.thinvent.remotepassword.service.ExtractService;
import com.thinvent.remotepassword.service.WikiDocDataService;
import com.thinvent.remotepassword.util.SimilarityUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.sql.Timestamp;
import java.util.*;

@Service("extractService")
public class ExtractServiceImpl extends ServiceImpl<WikiDocMapper, WikiDoc>  implements ExtractService {

    @Resource
    private WikiDocMapper wikiDocMapper;

    @Resource
    private WikiDocDataService wikiDocDataService;
    @Override
    public String extract(String docId) {
        // 根据文档id查询文档获取文档的存储地址 利用ftp的api获取文档并解析文档内容
        WikiDoc wikiDoc = wikiDocMapper.selectById(docId);
        if(null != wikiDoc) {
            try {
                File file = new File(wikiDoc.getPath());
                // 判断文件类型
                String fileName = file.getName();
                String extension = fileName.substring(fileName.lastIndexOf(".") + 1);

                if ("json".equalsIgnoreCase(extension)) {
                    System.out.println("这是一个JSON文件");
                    if (file.exists() && file.isFile()) {
                        // 读取响应内容
                        BufferedReader in = new BufferedReader(new FileReader(file));
                        StringBuilder content = new StringBuilder();
                        String inputLine;
                        while ((inputLine = in.readLine()) != null) {
                            content.append(inputLine);
                        }
                        in.close();

                        // 解析JSON数据为JSONArray
                        JSONArray jsonArray = JSON.parseArray(content.toString());

                        List<WikiDocData> wikiDocs = new ArrayList<>();

                        Date utilDate = new Date();
                        Timestamp timestampFromDate = new Timestamp(utilDate.getTime());

                        // 遍历并处理JSONArray中的每个元素
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject item = jsonArray.getJSONObject(i);
                            String question = item.getString("question");
                            System.out.println("question: " + question);

                            String answer = item.getString("answer");
                            System.out.println("answer: " + answer);

                            // 将question转化为向量
                            String vet = SimilarityUtil.getVet(question);
                            WikiDocData wikiDocData = new WikiDocData();
                            wikiDocData.setDocId(docId);
                            wikiDocData.setQuestion(vet);
                            wikiDocData.setAnswer(answer);

                            wikiDocData.setCreateTime(timestampFromDate);
                            wikiDocData.setUpdateTime(timestampFromDate);

                            wikiDocs.add(wikiDocData);
                        }
                        // 结束后入库
                        wikiDocDataService.saveBatch(wikiDocs);
                    }
                }
                if("xlsx".equalsIgnoreCase(extension)) {
                    System.out.println("这是一个Excel文件");
                    Map<Integer, ExcelRowData> rowDataMap = new HashMap<>();

                    // Read Sheet1
                    EasyExcel.read(wikiDoc.getPath(), ExcelRowData.class, new AnalysisEventListener<ExcelRowData>() {
                        @Override
                        public void invoke(ExcelRowData data, AnalysisContext context) {
                            rowDataMap.put(context.getCurrentRowNum(), data);
                        }

                        @Override
                        public void doAfterAllAnalysed(AnalysisContext context) {}
                    }).sheet(0).doRead();

                    // Read Sheet2 and combine with Sheet1 data
                    EasyExcel.read(wikiDoc.getPath(), new AnalysisEventListener<ExcelRowData>() {
                        @Override
                        public void invoke(ExcelRowData data, AnalysisContext context) {
                            Integer rowIndex = context.getCurrentRowNum();
                            if (rowDataMap.containsKey(rowIndex)) {
                                ExcelRowData combinedData = rowDataMap.get(rowIndex);
                                combinedData.setSheet2Data(data.getSheet1Data()); // Assuming Sheet2's data goes into Sheet1Data field for simplicity
                            } else {
                                // Handle missing row in Sheet1 if necessary
                            }
                        }

                        @Override
                        public void doAfterAllAnalysed(AnalysisContext context) {
                            // After all processing, print or further manipulate the map
                            rowDataMap.values().forEach(System.out::println);
                        }
                    }).sheet(1).doRead();
                    // 将map的数据转化为List<WikiDocData> wikiDocs = new ArrayList<>(); 并且入库
                    List<WikiDocData> wikiDocs = new ArrayList<>();
                    // 假设rowDataMap已经填充好了数据，现在转换数据
                    for (Map.Entry<Integer, ExcelRowData> entry : rowDataMap.entrySet()) {
                        ExcelRowData excelRowData = entry.getValue();
                        WikiDocData wikiDocData = new WikiDocData();

                        // 假设ExcelRowData的sheet1Data作为question，sheet2Data作为answer
                        wikiDocData.setQuestion(excelRowData.getSheet1Data());
                        wikiDocData.setAnswer(excelRowData.getSheet2Data());

                        // 设置docId，这里假设一个简单的生成规则，实际应根据业务需求
                        wikiDocData.setDocId(docId);

                        // 设置createTime和updateTime为当前时间
                        Date utilDate = new Date();
                        Timestamp timestampFromDate = new Timestamp(utilDate.getTime());
                        wikiDocData.setCreateTime(timestampFromDate);
                        wikiDocData.setUpdateTime(timestampFromDate);

                        wikiDocs.add(wikiDocData);
                    }
                    // 结束后入库
                    System.out.println("-------------" + JSON.toJSONString(wikiDocs));
                    wikiDocDataService.saveBatch(wikiDocs);
                }

                // 将状态改为已部署
                wikiDoc.setDeploy(true);
                wikiDocMapper.updateById(wikiDoc);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
